package org.spring.sample.service.zuul.filter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;

/**
 * zuul的过滤器
 *
 */
@Component
@Slf4j
public class IndexZuulFilter extends ZuulFilter {

	/**
	 * 过滤器的具体逻辑。可用很复杂，包括查sql，nosql去判断该请求到底有没有权限访问。
	 */
	@Override
	public Object run() {
		RequestContext context = RequestContext.getCurrentContext();
		HttpServletRequest request = context.getRequest();
		log.info("请求方法{}，请求路径{}", request.getMethod(), request.getRequestURL().toString());
		Object accessToken = request.getParameter("token");
		if (accessToken == null) {
			log.info("token 为空");
			context.setSendZuulResponse(false);
			context.setResponseStatusCode(401);
			try {
				context.getResponse().getWriter().write("token is empty");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 这里可以写逻辑判断，是否要过滤，本文true,永远过滤
	 */
	@Override
	public boolean shouldFilter() {
		return true;
	}

	/**
	 * 过滤的顺序
	 */
	@Override
	public int filterOrder() {
		return 0;
	}

	/**
	 * pre:路由之前 routing：路由之时 post：路由之后 error：发送错误调用
	 */
	@Override
	public String filterType() {
		return "pre";
	}

}
